import {
  getProductDetail,
  addToCar,
  loginWithCode,
  collectGoods,
  createDetailQrcode,
  getBeShared,
  getUseCoupon,
  detailLog,
  onlistShared
} from "../../../api.js"
var app = getApp().globalData
const QUALITY = {
  "9.5新": "整体成色较新，有轻微使用痕迹，品相完整.",
  "9.9新": "【未使用】商品状态完好.",
  "9.8新": "商品因陈列或存放导致极细微污渍、划痕、磨损等情况.",
  "9.0新": "外观有日常使用痕迹，局部有少数划痕、污渍、磨损等情况，品相良好",
  "8.5新": "外观有日常使用痕迹，局部有明显划痕、污渍、磨损等情况，品相普通.",
  "8.0新": "外观有长期使用痕迹，局部有较严重划痕、污渍、磨损等不影响正常使用",
}
Page({
  data: {
    te:false,
    activity_price:"",
    show: false,
    isAuth: true,
    height: 0,
    prod_id: 0,
    detail: true,
    describe: true,
    showImage: true,
    coupon_alert: true,
    couponLis: [],
    product: {
      pic_url: [],
      brand: "",
      title: "",
      quality: "",
      price: ""
    },
    erwei: '',
    header_img: '',
    alert_text1: true,
    alert_text2: true,
    alert_text3: true,
    alert_loading: false,
    alert: false,
    percent_n: 0,
    optionsText: [],
    purchase: false,
    indemnity: true,
    hidd:true,
    countDay: '',
    countDownHour: '',
    countDownMinute: '',
    countDownSecond: '',
    bargain_btn:false,
    bargain_typ:false
  },
  
  onLoad(options) {  
    let xp = this
    xp.setData({
      prod_id: options.id,
      ind: options.ind ? options.ind : '',
      optionsText: options
    })
    this.checkUserInfo()
    if (options.user_id) {
      getBeShared(getApp().globalData.Store.token, options.user_id, options.id).then(res => { })
    }
    var lisid = []
    lisid.push(options.id)
    getUseCoupon(
      getApp().globalData.Store.token,
      lisid
    ).then(res => {
      xp.setData({
        couponLis: res.data.data,
      })
    })
    if (options.enter_type) {
      detailLog(
        getApp().globalData.businessId,
        getApp().globalData.Store.token,
        options.id,
        options.enter_type,
        options.label ? options.label : '',
        options.position
      ).then(res => { })
    }    
    onlistShared({
      token: getApp().globalData.Store.user.id,
      source: options.source,
      parent_id: options.user_id,
      product_id: options.id,
    }).then(res => {
    })
    if (options.te == 2) {
      this.setData({
        te: true
      })
    }
  
  },
  onUnload() {

  },
  // 检查用户信息授权
  checkUserInfo() {
    const xp = this;
    let prodId = this.data.prod_id
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userInfo']) {
          // xp.setData({
          //   isAuth: false
          // })
          wx.navigateTo({
            url: '/pages/public/shouquan/shouquan',
          })
        } else {
          xp.setData({
            isAuth: true
          })

          wx.getUserInfo({
            success(res) {
              xp.loginWithCode(res.userInfo, prodId)
            }
          })
        }
      }
    })
  },

  //跳转至特价专区
  gob(){
    wx.navigateTo({
      url: '../../homepage/channelList/channelList?channelId=1',
    })
  },

  //登陆
  loginWithCode(userInfo, prod_id) {
    const xp = this
    wx.login({
      success({
        code
      }) {
        loginWithCode({
          ...userInfo,
          code,
          business_id: getApp().globalData.businessId
        }).then(res => {
          if (res.data.code === 666) {
            // sdk参数设置
            var optionsText = xp.data.optionsText
            getApp().globalData.Store = res.data.data
            let business = getApp().globalData.Store.business.id;
            let token = getApp().globalData.Store.token
            getProductDetail(business, prod_id, token).then(res => {
              if (res.data.code === 666) {
                wx.hideLoading()
                console.log(res.data.data[0].activity_price)
                xp.setData({
                  hidd: false,
                  activity_price: res.data.data[0].activity_price
                })
                if (xp.data.activity_price > 0 && xp.data.activity_price != null){
                  xp.setData({
                    te:true
                  })
                }else{
                  xp.setData({
                    te: false
                  })
                }
                xp.dealRep(res.data.data[0])
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "none"
                })
              }
              wx.hideLoading();
            })
            xp.getDynamicHeight();

          }
          wx.hideLoading()
        })
      }
    })
  },

  // 处理response
  dealRep(data) {
    let productInfo = data.full_name.split(" ")
    let product = {
      ...data,
      quality: productInfo[0],
      brand: productInfo[1],
      title: productInfo[2]
    }
    console.log("product")
    console.log(product)
    var that = this 
    if (data.cut_price || data.activity_price){      
      var now = new Date(data.cutPriceActivityTime.now.replace(/\-/g, "/")).getTime()
      var start_time = new Date(data.cutPriceActivityTime.activity_start_time.replace(/\-/g, "/")).getTime()
      var end_time = new Date(data.cutPriceActivityTime.activity_end_time.replace(/\-/g, "/")).getTime()
      if(now<start_time){
        that.countDown(data.cutPriceActivityTime.activity_start_time, data.cutPriceActivityTime.now)
      }else{
        that.countDown(data.cutPriceActivityTime.activity_end_time, data.cutPriceActivityTime.now)
        that.setData({
          bargain_typ: true
        })
      }
      if (now >= start_time) {
        that.setData({
          bargain_btn: true
        })
      }
    }
    this.setData({
      product
    })
  },
  getDynamicHeight() {
    let xp = this
    wx.getSystemInfo({
      success: (res) => {
        xp.setData({
          height: (res.windowHeight - res.windowWidth / 750) - 45
        })
      }
    })
  },
  // 自定义分享消息， title 商品名称 imageUrl 产品banner第一张
  onShareAppMessage(res) {
    return {
      title: this.data.product.full_name,
      imageUrl: this.data.product.pic_url,
      path: '/pages/public/productdetail/productdetail?id=' + this.data.product.id + '&user_id=' + getApp().globalData.Store.user.id+"&source="+4,
      // path: '/pages/public/productdetail/productdetail?source=' + 4 + "&product_id=" + this.data.product.id + '&parent_id=' + getApp().globalData.Store.user.id,
      success: (res) => { },
      fail: (res) => { }

    }
  },
  // 添加至购物车
  addToCar() {
    let id = this.data.product.id
    let token = getApp().globalData.Store.token
    let user = getApp().globalData.Store.user

    addToCar(token, [id]).then(res => {
      wx.showToast({
        title: res.data.msg,
        icon: "none"
      })
    })
  },
  // 立即购买
  buyImmediately() {
    /**
     * 处理小程序options encode编码 bug
     */
    let keyArr = Object.keys(this.data.product)
    let map = Object.create(null)
    let k;
    for (let i = 0, l = keyArr.length; i < l; i++) {
      k = keyArr[i]
      map[k] = encodeURIComponent(this.data.product[k])
    }
    wx.navigateTo({
      url: '/pages/money/settlement/settlement?product=' + JSON.stringify([map]) + '&order_enter_type=1'
    })
  },
  // 显示说明
  handleQualityToast() {
    this.setData({
      show: !this.data.show
    })
  },
  //已售空跳转页面
  btn_tab() {
    wx.navigateTo({
      url: '/pages/homepage/productList/productList?category_id=1',
    })
  },

  /*
    修改人：邵群
    修改时间；2018-11-16
    修改内容：点击按钮显示隐藏
  */
  expendDetail(e) {
    if (e.currentTarget.dataset.title == 'detail') {
      this.setData({
        detail: this.data.detail ? false : true
      })
    }
    if (e.currentTarget.dataset.title == 'describe') {
      this.setData({
        describe: this.data.describe ? false : true
      })
    }
    if (e.currentTarget.dataset.title == 'showImage') {
      this.setData({
        showImage: this.data.showImage ? false : true
      })
    }
    if (e.currentTarget.dataset.title == 'purchase') {
      this.setData({
        purchase: this.data.purchase ? false : true
      })
    }
    if (e.currentTarget.dataset.title == 'indemnity') {
      this.setData({
        indemnity: this.data.indemnity ? false : true
      })
    }
  },
  fenxq() {
    onlistShared({
      token: app.Store.token,
      source: 4,
      parent_id: app.Store.user.id,
      product_id: this.data.prod_id
    }).then(res => {
      console.log(res)
    })
  },
  saveImg() {
    var that = this
    that.setData({
      alert_loading: true
    })
    var thData = that.data.product
    var copyText = '';
    copyText = copyText + thData.full_name + '￥' + thData.price
    if (thData.group_people) {
      copyText = copyText + '\n适用人群：' + thData.group_people
    }
    if (thData.color) {
      copyText = copyText + '\n颜色：' + thData.color
    }
    if (thData.specification.length > 0) {
      copyText = copyText + '\n规格：'
      if (thData.specification[0].width) {
        copyText = copyText + '\t宽度' + thData.specification[0].width + 'cm'
      }
      if (thData.specification[0].height) {
        copyText = copyText + '\t高度' + thData.specification[0].height + 'cm'
      }
      if (thData.specification[0].longness) {
        copyText = copyText + '\t长度' + thData.specification[0].longness + 'cm'
      }
      if (thData.specification[0].size) {
        copyText = copyText + '\t肩带长' + thData.specification[0].size + 'cm'
      }
    }
    if (thData.material) {
      copyText = copyText + '\n材质：' + thData.material
    }
    if (thData.inside_structure) {
      copyText = copyText + '\n内里结构：' + thData.inside_structure
    }
    if (thData.specification[0].other) {
      copyText = copyText + '\n规格：' + thData.specification[0].other
    }
    if (thData.size) {
      copyText = copyText + '\n尺码：' + thData.size
    }
    if (thData.material) {
      copyText = copyText + '\n材质：' + thData.material
    }
    if (thData.mechanism) {
      copyText = copyText + '\n机芯类型：' + thData.mechanism
    }
    if (thData.watchshell.length > 0) {
      copyText = copyText + '\n表壳材质：'
      for (var i = 0; i < thData.watchshell.length; i++) {
        copyText = copyText + thData.watchshell[i] + '、'
      }
    }
    if (thData.diameter) {
      copyText = copyText + '\n表径：' + thData.diameter + 'cm'
    }
    if (thData.watchband.length > 0) {
      copyText = copyText + '\n表壳材质：'
      for (var i = 0; i < thData.watchband.length; i++) {
        copyText = copyText + thData.watchband[i] + '、'
      }
    }
    if (thData.fastener_type) {
      copyText = copyText + '\n表扣类型：' + thData.fastener_type
    }
    if (thData.waterproof) {
      copyText = copyText + '\n防水性能：' + thData.waterproof
    }
    if (thData.guarantee) {
      copyText = copyText + '\n防水保修：' + thData.guarantee
    }
    if (thData.producer) {
      copyText = copyText + '\n产地：' + thData.producer
    }
    if (thData.package.length > 0) {
      copyText = copyText + '\n包装清单：'
      for (var i = 0; i < thData.package.length; i++) {
        copyText = copyText + thData.package[i] + '、'
      }
    }
    if (thData.synopsis) {
      copyText = copyText + '\n小编推荐：' + thData.synopsis
    }
    if (thData.fineness_description) {
      copyText = copyText + '\n成色描述：' + thData.fineness_description
    }
    wx.setClipboardData({
      data: copyText,
      success: function (res) {
        that.setData({
          alert_text1: false
        })
        var pic_lis = that.data.product.pictures
        var pic_num = 0
        var pic_ty = 0
        if (pic_lis.length > 8) {
          pic_num = 8
        } else {
          pic_num = pic_lis.length
        }
        wx.showLoading({
          title: '正在下载图片...',
        })
        wx.downloadFile({
          url: pic_lis[pic_ty],
          success(res) {
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function (res) {
                pic_ty++
                if (pic_ty == pic_num) {
                  that.setData({
                    alert_text2: false
                  })
                  that.erweiuplod()
                } else {
                  wx.downloadFile({
                    url: pic_lis[pic_ty],
                    success(res) {
                      wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function (res) {
                          pic_ty++
                          if (pic_ty == pic_num) {
                            that.setData({
                              alert_text2: false
                            })
                            that.erweiuplod()
                          } else {
                            wx.downloadFile({
                              url: pic_lis[pic_ty],
                              success(res) {
                                wx.saveImageToPhotosAlbum({
                                  filePath: res.tempFilePath,
                                  success: function (res) {
                                    pic_ty++
                                    if (pic_ty == pic_num) {
                                      that.setData({
                                        alert_text2: false
                                      })
                                      that.erweiuplod()
                                    } else {
                                      wx.downloadFile({
                                        url: pic_lis[pic_ty],
                                        success(res) {
                                          wx.saveImageToPhotosAlbum({
                                            filePath: res.tempFilePath,
                                            success: function (res) {
                                              pic_ty++
                                              if (pic_ty == pic_num) {
                                                that.setData({
                                                  alert_text2: false
                                                })
                                                that.erweiuplod()
                                              } else {
                                                wx.downloadFile({
                                                  url: pic_lis[pic_ty],
                                                  success(res) {
                                                    wx.saveImageToPhotosAlbum({
                                                      filePath: res.tempFilePath,
                                                      success: function (res) {
                                                        pic_ty++
                                                        if (pic_ty == pic_num) {
                                                          that.setData({
                                                            alert_text2: false
                                                          })
                                                          that.erweiuplod()
                                                        } else {
                                                          wx.downloadFile({
                                                            url: pic_lis[pic_ty],
                                                            success(res) {
                                                              wx.saveImageToPhotosAlbum({
                                                                filePath: res.tempFilePath,
                                                                success: function (res) {
                                                                  pic_ty++
                                                                  if (pic_ty == pic_num) {
                                                                    that.setData({
                                                                      alert_text2: false
                                                                    })
                                                                    that.erweiuplod()
                                                                  } else {
                                                                    wx.downloadFile({
                                                                      url: pic_lis[pic_ty],
                                                                      success(res) {
                                                                        wx.saveImageToPhotosAlbum({
                                                                          filePath: res.tempFilePath,
                                                                          success: function (res) {
                                                                            pic_ty++
                                                                            if (pic_ty == pic_num) {
                                                                              that.setData({
                                                                                alert_text2: false
                                                                              })
                                                                              that.erweiuplod()
                                                                            } else {
                                                                              wx.downloadFile({
                                                                                url: pic_lis[pic_ty],
                                                                                success(res) {
                                                                                  wx.saveImageToPhotosAlbum({
                                                                                    filePath: res.tempFilePath,
                                                                                    success: function (res) {
                                                                                      pic_ty++
                                                                                      if (pic_ty == pic_num) {
                                                                                        that.setData({
                                                                                          alert_text2: false
                                                                                        })
                                                                                        that.erweiuplod()
                                                                                      }
                                                                                    },
                                                                                    fail(res) {
                                                                                      wx.showToast({
                                                                                        title: '下载失败请重新下载',
                                                                                        icon: 'none',
                                                                                        duration: 1000
                                                                                      })
                                                                                      that.setData({
                                                                                        alert_loading: false
                                                                                      })
                                                                                    }
                                                                                  })
                                                                                },
                                                                                fail(res) {
                                                                                  wx.showToast({
                                                                                    title: '下载失败请重新下载',
                                                                                    icon: 'none',
                                                                                    duration: 1000
                                                                                  })
                                                                                  that.setData({
                                                                                    alert_loading: false
                                                                                  })
                                                                                }
                                                                              })
                                                                            }
                                                                          },
                                                                          fail(res) {
                                                                            wx.showToast({
                                                                              title: '下载失败请重新下载',
                                                                              icon: 'none',
                                                                              duration: 1000
                                                                            })
                                                                            that.setData({
                                                                              alert_loading: false
                                                                            })
                                                                          }
                                                                        })
                                                                      },
                                                                      fail(res) {
                                                                        wx.showToast({
                                                                          title: '下载失败请重新下载',
                                                                          icon: 'none',
                                                                          duration: 1000
                                                                        })
                                                                        that.setData({
                                                                          alert_loading: false
                                                                        })
                                                                      }
                                                                    })
                                                                  }
                                                                }
                                                              })
                                                            },
                                                            fail(res) {
                                                              wx.showToast({
                                                                title: '下载失败请重新下载',
                                                                icon: 'none',
                                                                duration: 1000
                                                              })
                                                              that.setData({
                                                                alert_loading: false
                                                              })
                                                            }
                                                          })
                                                        }
                                                      },
                                                      fail(res) {
                                                        wx.showToast({
                                                          title: '下载失败请重新下载',
                                                          icon: 'none',
                                                          duration: 1000
                                                        })
                                                        that.setData({
                                                          alert_loading: false
                                                        })
                                                      }
                                                    })
                                                  },
                                                  fail(res) {
                                                    wx.showToast({
                                                      title: '下载失败请重新下载',
                                                      icon: 'none',
                                                      duration: 1000
                                                    })
                                                    that.setData({
                                                      alert_loading: false
                                                    })
                                                  }
                                                })
                                              }
                                            },
                                            fail(res) {
                                              wx.showToast({
                                                title: '下载失败请重新下载',
                                                icon: 'none',
                                                duration: 1000
                                              })
                                              that.setData({
                                                alert_loading: false
                                              })
                                            }
                                          })
                                        }
                                      })
                                    }
                                  },
                                  fail(res) {
                                    wx.showToast({
                                      title: '下载失败请重新下载',
                                      icon: 'none',
                                      duration: 1000
                                    })
                                    that.setData({
                                      alert_loading: false
                                    })
                                  }
                                })
                              },
                              fail(res) {
                                wx.showToast({
                                  title: '下载失败请重新下载',
                                  icon: 'none',
                                  duration: 1000
                                })
                                that.setData({
                                  alert_loading: false
                                })
                              }
                            })
                          }
                        }
                      })
                    },
                    fail(res) {
                      wx.showToast({
                        title: '下载失败请重新下载',
                        icon: 'none',
                        duration: 1000
                      })
                      that.setData({
                        alert_loading: false
                      })
                    }
                  })
                }
              },
              fail(res) {
                wx.showToast({
                  title: '下载失败请重新下载',
                  icon: 'none',
                  duration: 1000
                })
                that.setData({
                  alert_loading: false
                })
              }
            })
          }
        })
      }
    })
  },
  erweiuplod() {
    var that = this
    wx.downloadFile({
      url: that.data.erwei,
      success(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            setTimeout(function () {
              that.setData({
                alert_text3: false,
                alert_loading: false,
                alert: false
              })
              wx.hideLoading()
              wx.showToast({
                title: '图片下载完成',
              })
            }, 1500)
          }
        })
      }
    })
  },
  close_alert() {
    this.setData({
      alert: false
    })
  },
  alert_share_btn() {
    var that = this
    createDetailQrcode(getApp().globalData.Store.token, that.data.product.id).then(res => {
      that.setData({
        erwei: res.data.data.key,
        header_img: getApp().globalData.Store.user.topimageurl,
        header_name: getApp().globalData.Store.user.name
      })
    })
    onlistShared({
      token: getApp().globalData.Store.token,
      source:4,
      parent_id:"",
      product_id:that.data.product.id
    }).then(res=>{
    })
    this.setData({
      alert: true
    })

  },
  onShareAppMessage: function (res) {
    if (res.from === 'button') {

    }
    return {
      title: '转发',
      imageUrl: this.data.product.pic_url,
      path: '//pages/public/productdetail/productdetail?source=' + 4 + "&id=" + this.data.product.id + '&user_id=' + getApp().globalData.Store.user.id,
      success: function (res) {
        console.log('成功', res)
      }
    }
  },

  /**
   * 修改人：邵群
   * 修改时间：2018-11-28
   * 修改内容：首页的活动展示与跳转
   * */
  collect(e) {
    let product_id = String(e.currentTarget.dataset.id);
    let token = getApp().globalData.Store.token;
    collectGoods({
      product_id,
      token
    }).then(res => {
      if (res.data.code == 666) {
        let isCollect = 'product.user_wishlist'
        this.setData({
          [isCollect]: this.data.product.user_wishlist == 1 ? 0 : 1
        })
        if (this.data.product.user_wishlist == 0) {
          wx.showToast({
            title: '已取消收藏',
            icon: 'none',
          })
        } else if (this.data.product.user_wishlist == 1) {
          wx.showToast({
            title: '已成功收藏',
            icon: 'none',
          })
        }
        if (this.data.ind) {
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          prevPage.data.cateProductList.data[this.data.ind].user_wishlist = this.data.product.user_wishlist
          prevPage.setData({
            cateProductList: prevPage.data.cateProductList
          })
        }
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        let that = this;
        for (var i = 0; i < prevPage.data.productList.data.length; i++) {
          if (prevPage.data.productList.data[i].id == product_id) {
            if (that.data.product.user_wishlist == 0) {
              prevPage.data.productList.data[i].user_wishlist = 0
              prevPage.setData({
                productList: prevPage.data.productList
              })
            } else if (that.data.product.user_wishlist == 1) {
              prevPage.data.productList.data[i].user_wishlist = 1
              prevPage.setData({
                productList: prevPage.data.productList
              })
            }
          }
        }
      }
    })
  },
  coupon_alert_close() {
    this.setData({
      coupon_alert: true
    })
  },
  paymentCoupon() {
    var that = this
    that.setData({
      coupon_alert: false
    })
  },
  gocar() {
    wx.switchTab({
      url: '/pages/tabBar/shopcar/shopcar',
    })
    getApp().endpage(new Date().getTime())
  },
  onShow() {
    getApp().startpage(new Date().getTime())
   
  },
  onHide() {
    console.log('页面离开')
    getApp().endpage(new Date().getTime())
  },
  goindex() {
    wx.switchTab({
      url: '/pages/tabBar/index/index',
    })
    getApp().endpage(new Date().getTime())
  },
  zhiyoualert(){
    wx.showModal({
      title: '提示',
      content: '该商品为日本直接发货，EMS包邮，可追踪包裹进度，物流周期一般为7-10天。价格不含关税，海关抽检，若抽中后关税需有您自理。如需退运，往返日本运费由买家承担',
      showCancel:false,
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 倒计时
  // 倒计时
  countDown(endTime, nowTime) {
    var now = new Date(nowTime.replace(/\-/g, "/")).getTime()
    var end_time = new Date(endTime.replace(/\-/g, "/")).getTime()
    var totalSecond = (end_time - now) / 1000
    var interval = setInterval(function () {
      var second = totalSecond;
      var day = Math.floor((second) / 3600 / 24);
      var daStr = day.toString();
      var hr = Math.floor((second) / 3600);
      var hrStr = hr.toString() % 24;
      if (hrStr.length == 1) hrStr = '0' + hrStr;
      var min = Math.floor((second - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;
      var sec = second - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;
      this.setData({
        countDay: daStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        // wx.showToast({
        //   title: '活动已结束',
        // });
        this.setData({
          countDay: '0',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          // jieshu: true
        });
      }
    }.bind(this), 1000);
  },
  gobargain(){
    wx.navigateTo({
      url: '/pages/activity/list/list',
    })
  },
  gobargain_cen(e){
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/activity/details/details?id=' + id
    })
  }
})